﻿using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Rectangle = iTextSharp.text.Rectangle;

namespace PrinterMonitorSvc.Common
{
    /// <summary>
    /// Pdf帮助类
    /// </summary>
    public static class PdfHelper
    {
        /// <summary>
        /// 合成pdf文件
        /// </summary>
        /// <param name="fileList">文件名list</param>
        /// <param name="outMergeFile">输出路径</param>
        public static void MergePdfFiles(List<string> fileList, string outMergeFile)
        {
            PdfReader reader;
            Document document = new Document();

            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));
            document.Open();
            PdfContentByte cb = writer.DirectContent;
            PdfImportedPage newPage;
            for (int i = 0; i < fileList.Count; i++)
            {
                reader = new PdfReader(fileList[i]);
                int iPageNum = reader.NumberOfPages;
                for (int j = 1; j <= iPageNum; j++)
                {
                    var pageRotation = reader.GetPageRotation(j);
                    var pageWithRotation = reader.GetPageSizeWithRotation(j);
                    var pageWidth = pageWithRotation.Width;
                    var pageHeight = pageWithRotation.Height;

                    pageWithRotation.Left = 0;
                    pageWithRotation.Right = pageWidth;
                    pageWithRotation.Top = pageHeight;
                    pageWithRotation.Bottom = 0;

                    document.SetPageSize(pageWithRotation);
                    document.NewPage();
                    newPage = writer.GetImportedPage(reader, j);

                    //a左右拉伸 b左倾斜 c右倾斜  d上下拉伸 e左右平移 f上下平移
                    switch (pageRotation)
                    {
                        case 0:
                            cb.AddTemplate(newPage, 1f, 0, 0, 1f, 0, 0);
                            break;
                        case 90:
                            cb.AddTemplate(newPage, 0, -1f, 1f, 0, 0, pageHeight);
                            break;
                        case 180:
                            cb.AddTemplate(newPage, -1f, 0, 0, -1f, pageWidth, pageHeight);
                            break;
                        case 270:
                            cb.AddTemplate(newPage, 0, 1f, -1f, 0, pageHeight, 0);
                            break;
                        default:
                            cb.AddTemplate(newPage, 0, 0);
                            break;
                    }
                }
            }
            document.Close();

        }


    }
}
